<?php
namespace app\article\model;
use app\common\lib\Paginationm;
use think\Db;
use think\Controller;

class Articles extends Controller
{
    protected $beforeActionList = ['start'];
    public function start() {
        $this->itemType = 'article';
        $this->itemName = '内容';
        $this->item = 'Articles';
        $this->itemCategory = 'ArticlesCategory';
        $this->itemContent = 'ArticlesContent';
        $this->itemSearch = 'ArticlesSearch';
        $this->itemSearchRel = 'ArticlesSearchRel';
        $this->itemModelNameSpace = 'app\article\model\Articles';
        $this->itemCategoryModelNameSpace = 'app\article\model\ArticlesCategory';
        $this->itemTagsRelModelNameSpace = 'app\tag\model\TagsRel';
        $this->domain = config('domain');
        $this->settingInfo = config('settingInfo');
        $this->itemSettingInfo = config('articleSettingInfo');
    }
    
    public function itemAdd($paramData,$fieldList = null)
    {
    	if (!$paramData['title']) {
    		return false;
    	}
        if (!$paramData) {
            return false;
        }
        $itemInfo = db($this->item)->where('title',$paramData['title'])->find();
        if ($itemInfo) {
            return false;
        }
        if (config('addonsInfo')['articleImgLocal']) {
        	try{
            $paramData['content'] = model('addons\articleImgLocal\model\ArticleImgLocal')->index($paramData['content']);
            } catch(\Exception $e) {
            	
            }
        }
      	$uuid = uuid();
        $imgUrl  = $paramData['img_url'] ? $paramData['img_url'] : getImgUrlByContent($paramData['content']);
       	$imgUrlData =  $this->getImgUrlDataByContent($paramData['content']);
       	$imgUrlData = $imgUrlData ? json_encode($imgUrlData,true) : '';
        $paramData['description'] = $paramData['description'] ? $paramData['description'] : mb_substr(str_replace('"','',deleteHtml($paramData['content'])),0,88,'utf-8');
        $paramData['keywords'] = $paramData['keywords'] ? $paramData['keywords'] : $paramData['tags'];
        
        $indexId = db($this->item)->insertGetId(array (
            'uuid' => $uuid,
            'cid' => $paramData['cid'],
            'uid' => $paramData['uid'],
            'views' =>  $paramData['views'] ? $paramData['views'] : 0,
            'is_recommend' => $paramData['is_recommend'] ? $paramData['is_recommend'] : 0,
            'title' =>  $paramData['title'],
            'img_url' => $imgUrl,
            'publish_time' => $paramData['publish_time'] ? $paramData['publish_time'] : time(),
            'description' => $paramData['description'],
            'keywords' => $paramData['keywords'],
            'img_url_data' => $imgUrlData,
        ));
        $content = $paramData['content'];
        db($this->itemContent)->insert(array(
            'id' => $uuid,
            'content' => htmlspecialchars($content),
        ));
        if (is_array($fieldList) && $fieldList) {
            for ($i=0; $i < count($fieldList); $i++) { 
                $resArray[$fieldList[$i]['field']] = $fieldList[$i]['value'];
            }
        }
        if ($resArray) {
			try {
                db($this->item)->where('id',$indexId)->update($resArray);
	        } catch(\Exception $e) {}
        }
        $this->setSearchData($paramData['title'],$indexId);
        if ($paramData['tags']) {
            $tagsArray = explode(',',$paramData['tags']);
            model($this->itemTagsRelModelNameSpace)->itemAdd($tagsArray, $uuid,$this->itemType);
        }
        if ($paramData['specialId']) {
        	db('SpecialsRel')->insert(array(
                'special_id' =>  $paramData['specialId'],
                'item_id' =>  $indexId,
            ));
        }
        //更新数量
        $allTotal = db('Articles')->count();
        if (db('BaseKey')->where('key','article_num')->find()) {
        	db('BaseKey')->where('key','article_num')->update(array('val' => $allTotal));
        } else {
        	db('BaseKey')->insert(array('key' => 'article_num','val' => $allTotal));
        }
    	//更新用户数量
        db('Users')->where('uid',$paramData['uid'])->update([
            'article_num' => db('Articles')->where('uid',$paramData['uid'])->count(),
        ]);
        //推送
        if ($indexId) {
            $this->itemPush($indexId);
        }
        return $indexId;
    }
    public function itemEdit($paramData,$fieldList = [])
    {
        $indexInfo = db($this->item)->where('uuid',$paramData['uuid'])->find();
        if (!$indexInfo) {
            return false;
        }
        if (config('addonsInfo')['articleImgLocal']) {
        	try{
            $paramData['content'] = model('addons\articleImgLocal\model\ArticleImgLocal')->index($paramData['content']);
            } catch(\Exception $e) {
            	
            }
        }
        $indexId = $indexInfo['id'];
        $imgUrl  = $paramData['img_url'] ? $paramData['img_url'] : getImgUrlByContent($paramData['content']);
       	$imgUrlData =  $this->getImgUrlDataByContent($paramData['content']);
       	$imgUrlData = $imgUrlData ? json_encode($imgUrlData,true) : '';
        $paramData['description'] = $paramData['description'] ? $paramData['description'] : mb_substr(deleteHtml($paramData['content']),0,88,'utf-8');
        $paramData['keywords'] = $paramData['keywords'] ? $paramData['keywords'] : $paramData['tags'];
        db($this->item)->where('uuid',$paramData['uuid'])->update(array (
            'title' =>  $paramData['title'],
            'cid' => $paramData['cid'],
            'img_url' => $imgUrl,
            'edit_time' => time(),
            'description' => $paramData['description'],
            'keywords' => $paramData['keywords'],
            'img_url_data' => $imgUrlData,
        ));
        if ($paramData['views']) {
	        db($this->item)->where('uuid',$paramData['uuid'])->update(array (
	            'views' =>  $paramData['views'],
	        ));
        }
        $content = $paramData['content'];
        db($this->itemContent)->where('id',$indexInfo['uuid'])->update(array(
            'content' => htmlspecialchars($content),
        ));
        if (is_array($fieldList) && $fieldList) {
            for ($i=0; $i < count($fieldList); $i++) { 
                $resArray[$fieldList[$i]['field']] = $fieldList[$i]['value'];
            }
        }
    	if ($resArray) {
	        try {
				db($this->item)->where('id',$indexId)->update($resArray);     
	        } catch(\Exception $e) {}   
        }
        $this->setSearchData($paramData['title'],$indexId);
        if ($paramData['tags']) {
            $tagsArray = explode(',',$paramData['tags']);
            model($this->itemTagsRelModelNameSpace)->itemAdd($tagsArray, $indexInfo['uuid'],$this->itemType);
        }
        return $indexId;
    }
    
    public function getImgUrlDataByContent($htmlContent)
    {
        if (!$htmlContent) {
            return [];
        }
        preg_match_all('/<img.*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/', $htmlContent, $imagesArrays);
        if ($imagesArrays) {
            return $imagesArrays[1];
        }
        return [];
    }
    
    
    public function itemDel($id)
    {
        $indexId = $id;
        $itemInfo = db($this->item)->where('id',$id)->find();
        if (!$itemInfo) {
            return false;
        }
        db($this->item)->where('id',$id)->delete();
        db($this->itemContent)->where('id',$itemInfo['uuid'])->delete();
        db('TagsRel')->where('item_id',$itemInfo['uuid'])->delete();
        return true;
    }
    
    public function getItemInfo($id = null,$uuid = null,$itemInfo = null)
    {
        if (!$id && !$uuid && !$itemInfo) {
            return false;
        }
        if (!$itemInfo) {
        	if ($id) {
            	$itemInfo = db($this->item)->where('id',$id)->find(); 
        	}
        	if ($uuid) {
            	$itemInfo = db($this->item)->where('uuid',$uuid)->find(); 
        	}
            if (!$itemInfo) {
                return false;
            }
        }
        if ($itemInfo) {
            $itemInfo['categoryInfo'] = model($this->itemCategoryModelNameSpace)->getCategoryInfo($itemInfo['cid']);
            $itemInfo['img_url_data'] = $itemInfo['img_url_data'] ? json_decode($itemInfo['img_url_data'],true) : [];
            $itemInfo['firstImg'] = $itemInfo['img_url'] ? $itemInfo['img_url'] : config('domainStatic') . '/' . config('assets') . '/common/images/no-images.jpg';;
            $itemInfo['secondImg'] = $itemInfo['img_url_data'] ? $itemInfo['img_url_data'][1] : '';
            $itemInfo['thirdImg'] = $itemInfo['img_url_data'] ? $itemInfo['img_url_data'][2] : '';
            $itemInfo['url'] = $this->getUrlByItemInfo($itemInfo);
            $itemInfo['description'] = $this->getDescriptionByItemInfo($itemInfo);
	        try {
            	$itemInfo['userInfo'] = model('app\\user\\model\\Users')->getItemInfo($itemInfo['uid']);
	        } catch(\Exception $e) {}   
            return $itemInfo;
        }
    }
    
    public function getUrlByItemInfo($itemInfo,$paramDomain = null)
    {
        $domain = config('domain');
        $domain = $paramDomain ? $paramDomain : $domain;
        $itemId = $this->itemSettingInfo['uuidStatus'] ? 'uuid' : 'id';
        
        if ($itemInfo['categoryInfo'] && $itemInfo['categoryInfo']['id'] != 0) {
            $detailUrl = str_replace('<id>',$itemInfo[$itemId],$itemInfo['categoryInfo']['detailRule']);
            $detailUrl = str_replace('<time>',date('YmdHis',$itemInfo['publish_time']),$detailUrl);
            $url = $domain . $detailUrl;
        } else {
            $url = $domain . '/article/' . $itemInfo['id'] . '.html';
        }
        return $url;
    }
    
    public function getDescriptionByItemInfo($itemInfo)
    {
        return $itemInfo['description'] ? $itemInfo['description'] : mb_substr(deleteHtml($this->getContentByItemInfo($itemInfo)['content']),0,88,'utf-8');
    }
    
    public function getDescription($tag)
    {
        $tag = json_decode($tag,true);
        $itemId = isset($tag['itemId']) ? $tag['itemId'] : '';
        $contentInfo = db($this->itemContent)->where('id',$itemId)->find();
        return $contentInfo['description'] ? $contentInfo['description'] : mb_substr(deleteHtml(htmlspecialchars_decode($contentInfo['content'])),0,88,'utf-8');
    }
    
    public function getContentByItemInfo($itemInfo)
    {
        $indexId = $itemInfo['id'];
        $contentInfo = db($this->itemContent)->where('id',$itemInfo['uuid'])->find();
        $itemInfo['content'] = htmlspecialchars_decode($contentInfo['content']);
        $itemInfo['mipContent'] = model('app\common\model\Common')->getContentFilterByContent($itemInfo['content']);
        return $itemInfo;
    }
    
    public function setSearchData($title,$indexId)
    {
        $wordsArray = getWords($title);
        if ($indexId) {
            db($this->itemSearchRel)->where('item_id',$indexId)->delete();
            foreach ($wordsArray as $key => $value) {
                $searchInfo = db($this->itemSearch)->where('name',$value)->find();
                if (!$searchInfo) {
                    $searchId = db($this->itemSearch)->insertGetId(array(
                        'name' =>  $value,
                    ));
                    db($this->itemSearchRel)->insert(array(
                        'search_id' =>  $searchId,
                        'item_id' =>  $indexId,
                    ));
                } else {
                    db($this->itemSearchRel)->insert(array(
                        'search_id' =>  $searchInfo['id'],
                        'item_id' =>  $indexId,
                    ));
                }
            }
        }
        return $indexId;
    }
    
    public function getItemListByTag($tag,$listType)
    {
        $tag = json_decode($tag,true);
        $whereArray = [];
        if (!$tag) {
            return false;
        }
        foreach ($tag as $key => $val) {
            if (strpos($key, 'where') !== false) {
                if (strpos($val, '=') !== false) {
                    $tempVal = explode('=', $val);
                    $whereArray[trim($tempVal[0])] = trim($tempVal[1]);
                }
                if (strpos($val, '<>') !== false) {
                    $tempVal = explode('<>', $val);
                    $whereArray[trim($tempVal[0])] = ['<>',trim($tempVal[1])];
                    break;
                }
                if (strpos($val, 'like') !== false) {
                    $tempVal = explode('like', $val);
                    $whereArray[trim($tempVal[0])] = ['like',trim($tempVal[1])];
                }
                if (strpos($val, '>') !== false) {
                    $tempVal = explode('>', $val);
                    $whereArray[trim($tempVal[0])] = ['>',trim($tempVal[1])];
                }
                if (strpos($val, '<') !== false) {
                    $tempVal = explode('<', $val);
                    $whereArray[trim($tempVal[0])] = ['<',trim($tempVal[1])];
                }
            }
        }
        $tag['whereArray'] = $whereArray;
        if ($listType == 'list') {
            if ((isset($tag['tagNames']) && $tag['tagNames']) || (isset($tag['tagIds']) && $tag['tagIds'])) {
                return model($this->itemTagsRelModelNameSpace)->getItemListbyTagIds($tag);
            } else {
                if ((isset($tag['specialIds']) && $tag['specialIds'])) {
                    return model('app\special\model\SpecialsRel')->getItemListbySpecialIds($tag);     
                } else {
                    return $this->getItemList($tag);
                }
            }
        }
        if ($listType == 'pagination') {
            if ((isset($tag['tagNames']) && $tag['tagNames']) || (isset($tag['tagIds']) && $tag['tagIds'])) {
                return model($this->itemTagsRelModelNameSpace)->getPaginationbyTagIds($tag);
            } else {
                if ((isset($tag['specialIds']) && $tag['specialIds'])) {
                    return model('app\special\model\SpecialsRel')->getPaginationbySpecialIds($tag);     
                } else {
                    return $this->getPagination($tag);
                }
            }
        }
        
    }

    public function getItemList($paramData)
    {
        $cid = $paramData['cid'] ? $paramData['cid'] : null;
        $page = $paramData['page'] ? $paramData['page'] : 1;
        $limit = $paramData['limit'] ? $paramData['limit'] : 10;
        $orderBy = $paramData['orderBy'] ? $paramData['orderBy'] : 'publish_time';
        $order = $paramData['order'] ? $paramData['order'] : 'desc';
        $keywords = $paramData['keywords'] ? $paramData['keywords'] : null;
        $where = $paramData['where'] ? $paramData['where'] : null;
        $whereArray = $paramData['whereArray'] ? $paramData['whereArray'] : null;
        $ids = $paramData['ids'] ? $paramData['ids'] : null;
        $uuids = $paramData['uuids'] ? $paramData['uuids'] : null;
        $publishType = $paramData['publishType'] ? $paramData['publishType'] : null;
        $type = $paramData['type'] ? $paramData['type'] : '';
        $itemId = $paramData['itemId'] ? $paramData['itemId'] : '';
        $permissionType = $paramData['permissionType'] ? $paramData['permissionType'] : '';
        if ($type == 'rand') {
        	return model('app\\article\\model\\ArticlesExtend')->getItemRandList($paramData);
        }
        if ($type == 'about') {
        	return model('app\\article\\model\\ArticlesExtend')->getItemAboutList($paramData);
        }
        if ($type == 'love') {
        	return model('app\\article\\model\\ArticlesExtend')->getItemLoveList($paramData);
        }
        if ($type == 'week') {
        	return model('app\\article\\model\\ArticlesExtend')->getItemWeekList($paramData);
        }
        if ($type == 'month') {
        	return model('app\\article\\model\\ArticlesExtend')->getItemMonthList($paramData);
        }
        if ($type == 'search') {
        	return model('app\\article\\model\\ArticlesExtend')->getItemSearchList($paramData);
        }
        if ($ids) {
	        if (empty($ids)) {
	            $idsWhere = null;
	        } else {
	            $ids = explode(',',$ids);
	            $idsWhere['id']  = ['in',$ids];
	        }
        }
        if ($uuids) {
	        if (empty($uuids)) {
	            $idsWhere = null;
	        } else {
	            $uuids = explode(',',$uuids);
	            $idsWhere['uuid']  = ['in',$uuids];
	        }
        }
        if ($keywords) {
            $keywords = explode(',',$keywords);
            foreach ($keywords as $key => $val) {
                if ($val) {
                    $sq[] = "%".$val."%";
                }
            }
            $keywordsWhere['title']  = ['like',$sq,'OR'];
        }
        if ($cid == '' || $cid == null) {
            $cidWhere = null;
            $cidsWhere = null;
        } else {
            $cidArray = explode(',',$cid);
        	$cidCount = count($cidArray);
        	if ($cidCount == 1) {
	            $cidWhere['cid'] = $cid;
	            $data['pid'] = $cid;
	            $itemCategoryList = model($this->itemCategoryModelNameSpace)->getCategory($data);
	            if ($itemCategoryList) {
	                foreach ($itemCategoryList as $key => $value) {
	                    $cids[] = $value['id'];
	                }
	                $cidsWhere['cid']  = ['in',$cids];
	            }
        	} else {
	         	$cidsWhere['cid']  = ['in',$cidArray];
        	}
        }
        if ($permissionType != 'admin') {
		  	$cidHideWhere = null;
	        if ($cid == '' || $cid == null) {
		        $cidHideArray = db('ArticlesCategory')->field('id')->where('status',0)->select();
		        $hideCids = [];
		        if ($cidHideArray) {
		        	foreach ($cidHideArray as $key => $val) {
		        		$hideCids[] = $val['id'];
		        	}
		        	$cidHideWhere['cid'] = ['not in',$hideCids];
		        }
	        }
        }
        
        if ($idsWhere) {
            $itemList = db($this->item)->where($idsWhere)->order($orderBy,$order)->select();
        } else {
            $itemList = db($this->item)->where($keywordsWhere)->where($cidWhere)->whereOr($cidsWhere)->where($cidHideWhere)->where($where)->where($whereArray)->page($page,$limit)->order($orderBy,$order)->select();
        }
        if ($itemList) {
            foreach($itemList as $k => $v) {
                $itemList[$k] = $this->getItemInfo($v['id'],null,$v);
            }
        } else {
            $itemList = [];
        }
        return $itemList;
    }

    public function getPagination($paramData)
    {
        $cid = $paramData['cid'] ? $paramData['cid'] : null;
        $page = $paramData['page'] ? $paramData['page'] : 1;
        $limit = $paramData['limit'] ? $paramData['limit'] : 10;
        $keywords = $paramData['keywords'] ? $paramData['keywords'] : null;
        $whereArray = $paramData['whereArray'] ? $paramData['whereArray'] : null;
        $type = $paramData['type'] ? $paramData['type'] : '';
        if ($type == 'search') {
        	return model('app\\article\\model\\ArticlesExtend')->getItemSearchPagination($paramData);
        }
        
        $count = $this->getCount($cid,$keywords,$whereArray);
        $categoryInfo = model($this->itemCategoryModelNameSpace)->getCategoryInfo($cid);
        $baseUrl = $categoryInfo['url'];
        $pagination_array = array(
            'base_url' => $baseUrl,
            'total_rows' => $count,
            'per_page' => $limit,
            'cur_page' => $page,
            'page_break' => '_'
        );
        $pagination = new Paginationm($pagination_array);
        return $pagination->create_links();
    }
    
    public function getCount($cid = null,$keywords = null,$whereArray = null)
    {
        if ($keywords) {
            $keywords = explode(',',$keywords);
            foreach ($keywords as $key => $val) {
                if ($val) {
                    $sq[] = "%".$val."%";
                }
            }
            $keywordsWhere['title']  = ['like',$sq,'OR'];
        }
        if ($cid == '' || $cid == null) {
            $cidWhere = null;
            $cidsWhere = null;
        } else {
            $cidWhere['cid'] = $cid;
            $data['pid'] = $cid;
            $itemCategoryList = model($this->itemCategoryModelNameSpace)->getCategory($data);
            if ($itemCategoryList) {
                foreach ($itemCategoryList as $key => $value) {
                    $cids[] = $value['id'];
                }
                $cidsWhere['cid']  = ['in',$cids];
            }
        }
        $count = db($this->item)->where($keywordsWhere)->where($cidWhere)->whereOr($cidsWhere)->count();
        return $count;
    }
    public function updateViews($indexId)
    {
        $currentKey = 'views' . $indexId . md5(session_id());
        $tempCache =  db('ArticlesCache')->where('key',$currentKey)->find();
        if ($tempCache && $tempCache['add_time'] + 60 > time()) {
            return false;
        }
        $cacheItem = db('ArticlesCache')->limit(1)->find();
        if ($cacheItem) {
            if ($cacheItem['add_time'] <  strtotime(date('Y-m-d'))) {
                db('ArticlesCache')->where('add_time','<',time())->delete();
            }
        }
        db('ArticlesCache')->where('key',$currentKey)->delete();
        db('ArticlesCache')->insert(array('key' => $currentKey, 'add_time' => time()));
        db($this->item)->where('id',$indexId)->setInc('views', 1);
        return true;
    }
    
    public function getCrumb($tag)
    {
        $tag = json_decode($tag,true);
        $cid = isset($tag['cid']) ? $tag['cid'] : '';
        $ulClass = isset($tag['ulClass']) ? $tag['ulClass'] : 'site-crumb';
        $liClass = isset($tag['liClass']) ? $tag['liClass'] : '';
        $isHome = isset($tag['isHome']) ? $tag['isHome'] : 1;
        $separator = isset($tag['separator']) ? $tag['separator'] : '';
        $type = isset($tag['type']) ? $tag['type'] : '';
        $itemId = isset($tag['itemId']) ? $tag['itemId'] : '';
        
        if ($cid) {
            $categoryInfo = model($this->itemCategoryModelNameSpace)->getCategoryInfo($cid);
            if ($categoryInfo['pid'] == 0) {
                $html = '<ul class="list-unstyled ' . $ulClass . '">';
                $html .= intval($isHome) === 1 ? '<li class="' . $liClass .'"><a href="'. $this->domain .'" title="'. $this->settingInfo['siteName'] .'">首页</a>'.$separator.'</li>' : '';
                $html .= '<li class="' . $liClass .'">';
                $html .= '<a href="'. $categoryInfo['url'] .'" title="'. $categoryInfo['title'] .'">';
                $html .= $categoryInfo['title'];
                $html .= '</a>';
                $html .= '</li>';
                if ($itemId) {
                    $itemInfo = $this->getItemInfo($itemId);
                    $html .= '<li class="' . $liClass .'">';
                    $html .= '<a href="'. $itemInfo['url'] .'" title="'. $itemInfo['title'] .'">';
                    $html .= $itemInfo['title'];
                    $html .= '</a>';
                    $html .= '</li>';
                }
                $html .= '</ul>';
                return $html;
            } else {
                $html = '<ul class="list-unstyled ' . $ulClass . '">';
                $html .= intval($isHome) === 1 ? '<li class="' . $liClass .'"><a href="'. $this->domain .'" title="'. $this->settingInfo['siteName'] .'">首页</a>'.$separator.'</li>' : '';
                $html .= '<li class="' . $liClass .'">';
                $parentInfo = model($this->itemCategoryModelNameSpace)->getCategoryInfo($categoryInfo['pid']);
                $html .= '<a href="'. $parentInfo['url'] .'" title="'. $parentInfo['title'] .'">';
                $html .= $parentInfo['title'];
                $html .= '</a>'.$separator;
                $html .= '</li>';
                $html .= '<li class="' . $liClass .'">';
                $html .= '<a href="'. $categoryInfo['url'] .'" title="'. $categoryInfo['title'] .'">';
                $html .= $categoryInfo['title'];
                $html .= '</a>';
                $html .= '</li>';
                if ($itemId) {
                    $itemInfo = $this->getItemInfo($itemId);
                    $html .= '<li class="' . $liClass .'">';
                    $html .= '<a href="'. $itemInfo['url'] .'" title="'. $itemInfo['title'] .'">';
                    $html .= $itemInfo['title'];
                    $html .= '</a>';
                    $html .= '</li>';
                }
                $html .= '</ul>';
                return $html;
            }
        } else {
            $html = '<ul class="list-unstyled ' . $ulClass . '">';
            $html .= intval($isHome) === 1 ? '<li class="' . $liClass .'"><a href="'. $this->domain .'" title="'. $this->settingInfo['siteName'] .'">首页</a>'.$separator.'</li>' : '';
            $html .= '<li class="' . $liClass .'">';
            $html .= '<a href="'. config('domain') . '/' . $this->itemType . '/' .'" title="'. $this->itemName .'">';
            $html .= $this->itemName;
            $html .= '</a>';
            $html .= '</li>';
            if ($itemId) {
                $itemInfo = $this->getItemInfo($itemId);
                $html .= '<li class="' . $liClass .'">';
                $html .= '<a href="'. $itemInfo['url'] .'" title="'. $itemInfo['title'] .'">';
                $html .= $itemInfo['title'];
                $html .= '</a>';
                $html .= '</li>';
            }
            $html .= '</ul>';
            return $html;
        }
    }
    public function getPage($tag)
    {
        $tag = json_decode($tag,true);
        $itemId = isset($tag['itemId']) ? $tag['itemId'] : null;
        $limit = isset($tag['limit']) ? $tag['limit'] : 1;
        $page = isset($tag['page']) ? $tag['page'] : 1;
        $type = isset($tag['type']) ? $tag['type'] : 'detail';
        $itemType = isset($tag['itemType']) ? $tag['itemType'] : '';
        $cid = isset($tag['cid']) ? $tag['cid'] : '';
        
        if (!$itemId) {
            return false;
        }
        if ($cid == '' || $cid == null) {
            $cidWhere = null;
            $cidsWhere = null;
        } else {
            $cidWhere['cid'] = $cid;
            $data['pid'] = $cid;
            $itemCategoryList = model($this->itemCategoryModelNameSpace)->getCategory($data);
            if ($itemCategoryList) {
                foreach ($itemCategoryList as $key => $value) {
                    $cids[] = $value['id'];
                }
                $cidsWhere['cid']  = ['in',$cids];
            }
        }
        if ($type == 'detail') {
            if ($itemType == 'upPage') {
                $itemList = db($this->item)->where($cidWhere)->whereOr($cidsWhere)->where('id','<',$itemId)->limit($limit)->order('id','DESC')->select();
            }
            if ($itemType == 'downPage') {
                $itemList = db($this->item)->where($cidWhere)->whereOr($cidsWhere)->where('id','>',$itemId)->limit($limit)->order('id','ASC')->select();
            }
            if ($itemList) {
                foreach ($itemList as $k => $v) {
                    $itemList[$k] = $this->getItemInfo($v['id']); 
                }
                return $itemList;
            } else {
                return false;
            }
        }
    }
    
    public function itemPush($id)
    {
        if (!$id) {
            return false;
        }
        $itemInfo = $this->getItemInfo($id);
        $urls = explode(',',$itemInfo['url']);
        if (is_array($urls)) {
            if ($this->settingInfo['baiduMipApiStatus']) {
                $api = trim($this->settingInfo['baiduMipApi']);
                $result = pushData($api,$urls);
                $res = json_decode($result,true);
                if (!isset($res['error'])) {
                    db($this->item)->where('id',$itemInfo['id'])->update(array(
                        'mip_push_num' => $itemInfo['mip_push_num'] + 1,
                    ));
                }
            }
            if ($this->settingInfo['baiduTimeApiStatus']) {
                $api = trim($this->settingInfo['baiduTimeApi']);
                $result = pushData($api,$urls);
                $res = json_decode($result,true);
                if (!isset($res['error'])) {
                    db($this->item)->where('id',$itemInfo['id'])->update(array(
                        'link_push_num' => $itemInfo['link_push_num'] + 1,
                    ));
                }
            }
            if ($this->settingInfo['smApiStatus']) {
                $api = trim($this->settingInfo['smApi']);
                $result = pushData($api,$urls);
                $res = json_decode($result,true);
                if (!isset($res['error'])) {
                    db($this->item)->where('id',$itemInfo['id'])->update(array(
                        'sm_push_num' => $itemInfo['sm_push_num'] + 1,
                    ));
                }
            }
            if ($this->settingInfo['xzhRealtimeApiStatus']) {
                $api = trim($this->settingInfo['xzhRealtimeApi']);
                $result = pushData($api,$urls);
                $res = json_decode($result,true);
                if (!isset($res['error'])) {
                    db($this->item)->where('id',$itemInfo['id'])->update(array(
                        'xzh_realtime_push_num' => $itemInfo['xzh_realtime_push_num'] + 1,
                    ));
                }
            }
            if ($this->settingInfo['xzhBatchApiStatus']) {
                $api = trim($this->settingInfo['xzhBatchApi']);
                $result = pushData($api,$urls);
                $res = json_decode($result,true);
                if (!isset($res['error'])) {
                    db($this->item)->where('id',$itemInfo['id'])->update(array(
                        'xzh_batch_push_num' => $itemInfo['xzh_batch_push_num'] + 1,
                    ));
                }
            }
          	$type = config('keyInfo')['baiduAppAutoType'];
            if ($type) {
            	if ($type == 'week') {
            		$tempType = 0;
            	}
            	if ($type == 'day') {
            		$tempType = 1;
            	}
            	if ($type == 'hour') {
            		$tempType = 2;
            	}
        		model('addons\baiduAppPushVip\model\BaiduAppPushVip')->baiduAppPush($id,$tempType);
            }
        }
        return $result;

    }
    /**
     * 根据分类ID查询权限
     */
    public function getUserGroupExtendData($cid = 0,$groupId = null,$categoryInfo = null)
    {
    	$userInfo = config('userInfo');
    	$groupId = $groupId ? $groupId : $userInfo['group_id'];
    	if (!$categoryInfo) {
	    	if ($cid == 0) {
	    		$categoryInfo['id'] = 0;
	    	} else {
    			$categoryInfo = model($this->itemCategoryModelNameSpace)->getCategoryInfo($cid);
	    	}
    	}
		$data = $this->getUserGroupExtendInfo($groupId,0);
		if (!$categoryInfo['id']) {
			return $data;			
		}
		//一级操作
    	if ($categoryInfo['pid'] == 0) {
			$data = $this->getUserGroupExtendLevel($data,$groupId,$categoryInfo['id']);
    	} else {
			$data = $this->getUserGroupExtendLevel($data,$groupId,$categoryInfo['pid']);
			$data = $this->getUserGroupExtendLevel($data,$groupId,$categoryInfo['id']);
    	}
    	return $data;
    }
    
    public function getUserGroupExtendLevel($data,$groupId,$cid)
    {
		$userGroupExtendInfo = $this->getUserGroupExtendInfo($groupId,$cid);
		if ($userGroupExtendInfo) {
			if ($userGroupExtendInfo['articlePublish'] != 2) {
				$data['articlePublish'] = $userGroupExtendInfo['articlePublish'];
			}
			if ($userGroupExtendInfo['articlePublishVerify'] != 2) {
				$data['articlePublishVerify'] = $userGroupExtendInfo['articlePublishVerify'];
			}
			if ($userGroupExtendInfo['articlePublishDel'] != 2) {
				$data['articlePublishDel'] = $userGroupExtendInfo['articlePublishDel'];
			}
			if ($userGroupExtendInfo['articlePublishEdit'] != 2) {
				$data['articlePublishEdit'] = $userGroupExtendInfo['articlePublishEdit'];
			}
			if ($userGroupExtendInfo['articlePublishNum'] != -1) {
				$data['articlePublishNum'] = $userGroupExtendInfo['articlePublishNum'];
			}
			
			if ($userGroupExtendInfo['articleComment'] != 2) {
				$data['articleComment'] = $userGroupExtendInfo['articleComment'];
			}
			if ($userGroupExtendInfo['articleCommentVerify'] != 2) {
				$data['articleCommentVerify'] = $userGroupExtendInfo['articleCommentVerify'];
			}
			if ($userGroupExtendInfo['articleCommentDel'] != 2) {
				$data['articleCommentDel'] = $userGroupExtendInfo['articleCommentDel'];
			}
			if ($userGroupExtendInfo['articleCommentEdit'] != 2) {
				$data['articleCommentEdit'] = $userGroupExtendInfo['articleCommentEdit'];
			}
			if ($userGroupExtendInfo['articleCommentNum'] != -1) {
				$data['articleCommentNum'] = $userGroupExtendInfo['articleCommentNum'];
			}
			
			//管理
			if ($userGroupExtendInfo['articleElite'] != 2) {
				$data['articleElite'] = $userGroupExtendInfo['articleElite'];
			}
			if ($userGroupExtendInfo['articleTop'] != 2) {
				$data['articleTop'] = $userGroupExtendInfo['articleTop'];
			}
			if ($userGroupExtendInfo['articleRecommend'] != 2) {
				$data['articleRecommend'] = $userGroupExtendInfo['articleRecommend'];
			}
			if ($userGroupExtendInfo['articleDel'] != 2) {
				$data['articleDel'] = $userGroupExtendInfo['articleDel'];
			}
		}
		return $data;
    }
    
    public function getUserGroupExtendInfo($groupId,$cid = 0)
    {
    	$data = [];
		$articleUserGroupExtendList = config('articleUserGroupExtendList');
		if (!$articleUserGroupExtendList) {
			$articleUserGroupExtendList = db('ArticlesUsersGroupExtend')->select();
			config('articleUserGroupExtendList',$articleUserGroupExtendList);
			$articleUserGroupExtendList = config('articleUserGroupExtendList');
		}
		if ($articleUserGroupExtendList) {
			foreach ($articleUserGroupExtendList as $key => $val) {
				if ($val['cid'] == $cid && $val['item_id'] == $groupId) {
					$userGroupExtendInfo = $val;
				}
			}
		}
		if (!$userGroupExtendInfo) {
			if ($cid == 0) { //初始化
	    		$data['articlePublish'] = 1;
	    		$data['articlePublishVerify'] = 1;
	    		$data['articlePublishDel'] = 1;
	    		$data['articlePublishEdit'] = 1;
	    		$data['articlePublishNum'] = 10;
	    		$data['articleComment'] = 1;
	    		$data['articleCommentVerify'] = 0;
	    		$data['articleCommentDel'] = 1;
	    		$data['articleCommentEdit'] = 1;
	    		$data['articleCommentNum'] = 100;
	    		//管理
	    		$data['articleElite'] = 0;
	    		$data['articleTop'] = 0;
	    		$data['articleRecommend'] = 0;
	    		$data['articleDel'] = 0;
			} else { //2继承上级 
	    		$data['articlePublish'] = 2;
	    		$data['articlePublishVerify'] = 2;
	    		$data['articlePublishDel'] = 2;
	    		$data['articlePublishEdit'] = 2;
	    		$data['articlePublishNum'] = -1;
	    		$data['articleComment'] = 2;
	    		$data['articleCommentVerify'] = 2;
	    		$data['articleCommentDel'] = 2;
	    		$data['articleCommentEdit'] = 2;
	    		$data['articleCommentNum'] = -1;
	    		//管理
	    		$data['articleElite'] = 2;
	    		$data['articleTop'] = 2;
	    		$data['articleRecommend'] = 2;
	    		$data['articleDel'] = 2;
			}
		} else {
			$jsonStr = $userGroupExtendInfo['data'] ? $userGroupExtendInfo['data'] : "[]";
    		$dataArray = json_decode($jsonStr,true);
    		if ($cid == 0) {
	    		$data['articlePublish'] = isset($dataArray['articlePublish']) ? intval($dataArray['articlePublish']) : 1;
	    		$data['articlePublishVerify'] = isset($dataArray['articlePublishVerify']) ? intval($dataArray['articlePublishVerify']) : 1;
	    		$data['articlePublishDel'] = isset($dataArray['articlePublishDel']) ? intval($dataArray['articlePublishDel']) : 1;
	    		$data['articlePublishEdit'] = isset($dataArray['articlePublishEdit']) ? intval($dataArray['articlePublishEdit']) : 1;
	    		$data['articlePublishNum'] = isset($dataArray['articlePublishNum']) ? intval($dataArray['articlePublishNum']) : 10;
	    		
	    		$data['articleComment'] = isset($dataArray['articleComment']) ? intval($dataArray['articleComment']) : 1;
	    		$data['articleCommentVerify'] = isset($dataArray['articleCommentVerify']) ? intval($dataArray['articleCommentVerify']) : 0;
	    		$data['articleCommentDel'] = isset($dataArray['articleCommentDel']) ? intval($dataArray['articleCommentDel']) : 1;
	    		$data['articleCommentEdit'] = isset($dataArray['articleCommentEdit']) ? intval($dataArray['articleCommentEdit']) : 1;
	    		$data['articleCommentNum'] = isset($dataArray['articleCommentNum']) ? intval($dataArray['articleCommentNum']) : 100;
	    		
	    		$data['articleElite'] = isset($dataArray['articleElite']) ? intval($dataArray['articleElite']) : 0;
	    		$data['articleTop'] = isset($dataArray['articleTop']) ? intval($dataArray['articleTop']) : 0;
	    		$data['articleRecommend'] = isset($dataArray['articleRecommend']) ? intval($dataArray['articleRecommend']) : 0;
	    		$data['articleDel'] = isset($dataArray['articleDel']) ? intval($dataArray['articleDel']) : 0;
    		} else {
    			
	    		$data['articlePublish'] = isset($dataArray['articlePublish']) ? intval($dataArray['articlePublish']) : 2;
	    		$data['articlePublishVerify'] = isset($dataArray['articlePublishVerify']) ? intval($dataArray['articlePublishVerify']) : 2;
	    		$data['articlePublishDel'] = isset($dataArray['articlePublishDel']) ? intval($dataArray['articlePublishDel']) : 2;
	    		$data['articlePublishEdit'] = isset($dataArray['articlePublishEdit']) ? intval($dataArray['articlePublishEdit']) : 2;
	    		$data['articlePublishNum'] = isset($dataArray['articlePublishNum']) ? intval($dataArray['articlePublishNum']) : -1;
	    		
	    		$data['articleComment'] = isset($dataArray['articleComment']) ? intval($dataArray['articleComment']) : 2;
	    		$data['articleCommentVerify'] = isset($dataArray['articleCommentVerify']) ? intval($dataArray['articleCommentVerify']) : 2;
	    		$data['articleCommentDel'] = isset($dataArray['articleCommentDel']) ? intval($dataArray['articleCommentDel']) : 2;
	    		$data['articleCommentEdit'] = isset($dataArray['articleCommentEdit']) ? intval($dataArray['articleCommentEdit']) : 2;
	    		$data['articleCommentNum'] = isset($dataArray['articleCommentNum']) ? intval($dataArray['articleCommentNum']) : -1;
	    		
	    		$data['articleElite'] = isset($dataArray['articleElite']) ? intval($dataArray['articleElite']) : 2;
	    		$data['articleTop'] = isset($dataArray['articleTop']) ? intval($dataArray['articleTop']) : 2;
	    		$data['articleRecommend'] = isset($dataArray['articleRecommend']) ? intval($dataArray['articleRecommend']) : 2;
	    		$data['articleDel'] = isset($dataArray['articleDel']) ? intval($dataArray['articleDel']) : 2;
    		}
    		
		}
    	return $data;
    }

}